package Tree;

import java.util.Arrays;

public class Tarjan {

    public static int MAXN = 50_0001;
    // 链式前向星建图
    public static int[] headEdge = new int[MAXN];

    public static int[] edgeNext = new int[MAXN << 1];

    public static int[] edgeTo = new int[MAXN << 1];

    public static int tcnt;
    // 每个节点有哪些查询，也用链式前向星方式存储
    public static int[] headQuery = new int[MAXN];

    public static int[] queryNext = new int[MAXN << 1];

    public static int[] queryTo = new int[MAXN << 1];

    // 问题的编号，一旦有答案就可以知道填写在那
    public static int[] queryIndex = new int[MAXN << 1];

    public static int qcnt;

    // 某个节点是否访问过
    public static boolean[] visited = new boolean[MAXN];

    // 并查集
    public static int[] father = new int[MAXN];

    // 收集的答案
    public static int[] ans = new int[MAXN];

    public static void build(int n) {
        // 清空问题和树的链式前向星
        tcnt = qcnt = 1;
        Arrays.fill(headEdge, 1, n + 1, 0);
        Arrays.fill(headQuery, 1, n + 1, 0);
        Arrays.fill(visited, 1, n + 1, false);

        for (int i = 1; i <= n; i++) {
            father[i] = i;
        }
    }

    public static void addEdge(int u, int v) {
        edgeNext[tcnt] = headEdge[u];
        edgeTo[tcnt] = v;
        headEdge[u] = tcnt++;
    }

    public static void addQuery(int u, int v, int i) {
        queryNext[qcnt] = headQuery[u];
        queryTo[qcnt] = v;
        queryIndex[qcnt] = i;
        headQuery[u] = qcnt++;
    }

    /**
     * 并查集找头节点 递归版
     *
     * @param i
     * @return
     */
    public static int find(int i) {
        if (i != father[i]) {
            father[i] = find(father[i]);
        }
        return father[i];
    }

    public static void tarjan(int u, int f) {
        visited[u] = true;

        for (int e = headEdge[u], v; e != 0; e = edgeNext[e]) {
            v = edgeTo[e];
            if (v != f) {
                tarjan(v, u);
                father[v] = u;
            }
        }

        for (int e = headQuery[u], v; e != 0; e = queryNext[e]) {
            v = queryTo[e];
            if (visited[v]) {
                ans[queryIndex[e]] = find(v);
            }
        }
    }
}
